package nevigation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import map.DrawMap;

import calculate.BeaconData;
import calculate.Triangulation;

import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.estimote.sdk.Utils;
import com.example.nevigation.R;

import a_star.Map;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final String TAG = MainActivity.class.getSimpleName();

	private static final int REQUEST_ENABLE_BT = 1234;
	private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
	private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region(
			ESTIMOTE_PROXIMITY_UUID, null, null);

	private BeaconManager beaconManager;
	BeaconData[] beaconArr = new BeaconData[3];
	List<Beacon> beacons;
	String[] macAdd = { "E1:A8:40:9A:FB:48", "D8:F0:8B:45:46:64",
			"D1:F6:41:76:5A:7A" };

	DrawMap map;
	BackgroundUi backgroundUi = new BackgroundUi();

	int count = 0;
	double[] sum = new double[3];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Configure device list.

		// Configure BeaconManager.
		beaconManager = new BeaconManager(this);
		beaconManager.setRangingListener(new BeaconManager.RangingListener() {
			@Override
			public void onBeaconsDiscovered(Region region,
					final List<Beacon> beacon) {
				// Note that results are not delivered on UI thread.
				beacons = beacon;
				backgroundUi.doInBackground(null);
			}
		});
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) {
	 * getMenuInflater().inflate(R.menu.scan_menu, menu); MenuItem refreshItem =
	 * menu.findItem(R.id.refresh);
	 * refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
	 * return true; }
	 */
	@Override
	protected void onDestroy() {
		beaconManager.disconnect();

		super.onDestroy();
	}

	@Override
	protected void onStart() {
		super.onStart();

		// Check if device supports Bluetooth Low Energy.
		if (!beaconManager.hasBluetooth()) {
			Toast.makeText(this, "Device does not have Bluetooth Low Energy",
					Toast.LENGTH_LONG).show();
			return;
		}

		// If Bluetooth is not enabled, let user enable it.
		if (!beaconManager.isBluetoothEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			connectToService();
		}
	}

	@Override
	protected void onStop() {
		try {
			beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
		} catch (RemoteException e) {
			Log.d(TAG, "Error while stopping ranging", e);
		}

		super.onStop();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT) {
			if (resultCode == Activity.RESULT_OK) {
				connectToService();
			} else {
				Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
						.show();
				getActionBar().setSubtitle("Bluetooth not enabled");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void connectToService() {
		getActionBar().setSubtitle("Scanning...");
		beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
			@Override
			public void onServiceReady() {
				try {
					beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
					Log.d("--------------", "---------------");
				} catch (RemoteException e) {
					// Toast.makeText(ListBeaconsActivity.this,
					// "Cannot start ranging, something terrible happened",
					// Toast.LENGTH_LONG).show();
					Log.e(TAG, "Cannot start ranging", e);
				}
			}
		});
	}

	private class BackgroundUi extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			if (beacons.size() >= 3) {
				beaconArr[0] = new BeaconData();
				beaconArr[1] = new BeaconData();
				beaconArr[2] = new BeaconData();

				beaconArr[0].setMacAdd(beacons.get(0).macAddress);
				beaconArr[1].setMacAdd(beacons.get(1).macAddress);
				beaconArr[2].setMacAdd(beacons.get(2).macAddress);

				double b1 = Utils.computeAccuracy(beacons.get(0));
				double b2 = Utils.computeAccuracy(beacons.get(1));
				double b3 = Utils.computeAccuracy(beacons.get(2));

				/*b1 = b1 * 3;
				b2 = b2 * 3;
				b3 = b3 * 3;*/
				Log.d("beaconv", "b1 : " + b1 + "  b2 : " + b2 + "  b3 : " + b3);
				beaconArr[0].setDistance(b1);
				beaconArr[1].setDistance(b2);
				beaconArr[2].setDistance(b3);

				Triangulation t = new Triangulation(beaconArr);
				BeaconData a = t.getPosition();

				float x = (float) (a.getX());
				float y = (float) (a.getY());

				if (x > 49 && y > 49) {
					Toast.makeText(getApplicationContext(), "범위초과", Toast.LENGTH_SHORT).show();
				} else {
					Log.d("xy", "x :" + a.getX() + "  y :" + a.getY());

					getActionBar().setSubtitle("x : " + x + "  y : " + y);

					setContentView(new DrawMap(getApplicationContext(), x, y, b1, b2, b3));
					Log.d("doInbackground", "doInbackground");
				}
			}
			/* } */
			return null;
		}
	}
}
